package com.winit.cloudlink.mgmt.heartbeat;

import com.google.common.collect.Maps;
import com.winit.cloudlink.Cloudlink;
import com.winit.cloudlink.common.AppID;
import com.winit.cloudlink.message.Message;
import com.winit.cloudlink.mgmt.heartbeat.utils.IdGenerator;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

/**
 * Created by stvli on 2017/3/28.
 */
@Component
public class HeartbeatMessageSender implements InitializingBean {
    public static final Map<String, String[]> toAppIdCache = Maps.newLinkedHashMap();

    static {
        toAppIdCache.put("CNR", new String[]{"CLOUDLINK-HEARBEAT-US.CLOUDLINK-HEARBEAT.ALL.USR", "CLOUDLINK-HEARBEAT-EU.CLOUDLINK-HEARBEAT.ALL.EUR", "CLOUDLINK-HEARBEAT-AU.CLOUDLINK-HEARBEAT.ALL.AUR"});
        toAppIdCache.put("USR", new String[]{"CLOUDLINK-HEARBEAT-CN.CLOUDLINK-HEARBEAT.ALL.CNR"});
        toAppIdCache.put("EUR", new String[]{"CLOUDLINK-HEARBEAT-CN.CLOUDLINK-HEARBEAT.ALL.CNR"});
        toAppIdCache.put("AUR", new String[]{"CLOUDLINK-HEARBEAT-CN.CLOUDLINK-HEARBEAT.ALL.CNR"});
    }

    private String[] toAppIds;


    @Resource
    private Cloudlink cloudlink;


    @Scheduled(fixedRate = 1000 * 30)//每30秒执行一次
    public void sendMessage() {
        for (String appId : toAppIds) {
            cloudlink.sendMessage(buildMessage(new AppID(appId)));
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.notNull(cloudlink);
        toAppIds = toAppIdCache.get(cloudlink.getMetadata().getCurrentZone().getName());
        Assert.notEmpty(toAppIds);
    }

    private Message<HeartbeatInfo> buildMessage(AppID appID) {
        HeartbeatInfo payload = new HeartbeatInfo();
        payload.setTraceNo(String.valueOf(IdGenerator.nextId(appID.getArea())));
        payload.setCreated(new Date());
        return cloudlink.newMessageBuilder().direct(appID.toString(), HeartbeatInfo.MESSAGE_TYPE, payload).build();
    }


}
